# encoding:utf-8

import json
import os.path

from aip import AipOcr

""" 你的 APPID AK SK """
APP_ID = '18129119'
API_KEY = 'ytODxCCIsZtkjPnDCHYCRqsz'
SECRET_KEY = 'XNTUgVPtFVWSYMoFtiLXcAyEo2SSbpby'

client = None

""" 读取图片 """


def get_content(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        result = json.load(f)
    return result


def analyze_local_image(image_path, result_path=None):
    global client

    if result_path and os.path.exists(result_path):
        return get_content(result_path)

    if not os.path.exists(image_path):
        return {}

    with open(image_path, 'rb') as fp:
        image = fp.read()

    if not client:
        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

    """ 调用通用文字识别（含位置信息版）, 图片参数为本地图片 """
    client.general(image)

    """ 如果有可选参数 """
    options = {}
    options["recognize_granularity"] = "big"
    options["language_type"] = "CHN_ENG"
    options["detect_direction"] = "false"
    options["detect_language"] = "false"
    options["paragraph"] = "false"
    options["vertexes_location"] = "true"
    options["probability"] = "true"

    """ 带参数调用通用文字识别（含位置信息版）, 图片参数为本地图片 """
    result = client.general(image, options)

    if result_path:
        with open(result_path, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=4)
    return result


def analyze_online_image(url):
    """ 调用通用文字识别（含位置信息版）, 图片参数为远程url图片 """
    client.generalUrl(url)

    """ 如果有可选参数 """
    options = {}
    options["recognize_granularity"] = "big"
    options["language_type"] = "CHN_ENG"
    options["detect_direction"] = "true"
    options["detect_language"] = "true"
    options["vertexes_location"] = "true"
    options["probability"] = "true"

    """ 带参数调用通用文字识别（含位置信息版）, 图片参数为远程url图片 """
    client.generalUrl(url, options)
